import { getTenantID, requestFunComponFiex } from '@/utils';
import { useRequest } from 'umi';
import { BZWC_STATE, CQXG_STATE, DB_STATE, LB_STATE, LRKPB_STATE, YDB_STATE, generateRandomNumber, DWC_STATE } from '../common/Format';
import { ExpertsManageCurRes, sourceManageTab } from '../mconfig/ManageTabSwitch';
import { useMemo, useState, useEffect } from 'react';
import { ManageCommonAPI } from '@/pages/type';
import { searchCriteriaFun } from '../../Acommon';
import { ILoadMapTypeAll } from '@/common';
import { getBaseUrl } from '@/services/urlconst';

const baseUrl = getBaseUrl();

/** 采购实施管理页接口 */
export const SourceManageService = (curRes, locationProps) => {
  /**
   * 保存数据
   * */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>();

  const request = useRequest(
    (requestParams?: Record<string, any>) => {
      let params: any = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        state: [BZWC_STATE(), DWC_STATE(), CQXG_STATE(), LRKPB_STATE(), DB_STATE(), YDB_STATE(), LB_STATE()]?.join(','),
        ...sourceManageTab(curRes),
        ...requestParams,
      };
      const reqUrl = `${baseUrl}/purchaseSourceController/dataGrid/${params?.params}`;

      /**
       * 处理数据时间，人格式
       * */
      params = searchCriteriaFun(params);

      /**
       * 如果(statistics_sourceIds)存在，则是从采购供应商统计跳转，需要将他赋值到id上
       * */
      if (locationProps?.state?.statistics_sourceIds) {
        params.id = locationProps?.state?.statistics_sourceIds;
      }

      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: false,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  const requestManage = (otherRequest: ManageCommonAPI.IGridRequestType | any) => request.run(otherRequest);

  useEffect(() => {
    if (request.data?.rows?.length > 0) {
      let data = request.data?.rows;
      data?.forEach((item) => {
        if (item?.abortiveNum > 0) {
          item.children = [];
        }
      });
      setDataSource(data);
    } else {
      setDataSource([]);
    }
  }, [request.data?.rows]);

  return {
    SourceRun: request.run,
    SourceData: dataSource,
    setDataSource,
    SourceLoading: request.loading,
    SourceTableProps: request.tableProps,
    requestManage,
  };
};

/** 招标公告选择项目dataGrid接口 */
// export const ApplyManageService = () => {
//   /**管理页列表接口 */
//   const getApplyManageService = () => {
//     const request = useRequest(
//       (requestParams?: Record<string, any>) => {
//         let params: any = {
//           createCompanyID: getLevelZero(),
//           current: 1,
//           pageSize: 10,
//           ...requestParams,
//         };
//         const reqUrl = `${baseUrl}/purchaseApplyController/dataGrid/createCompanyID`;

//         delete params['applyFormNameDept'];
//         delete params['applyFormNameUser'];
//         if (params['createrID']?.length) {
//           params['createrID'] = params['createrID']?.toString();
//         } else {
//           delete params['createrID'];
//         }
//         return requestFunComponFiex('POST', reqUrl, params);
//       },
//       {
//         manual: false,
//         paginated: true,
//         defaultPageSize: 10,
//       },
//     );

//     return {
//       applyManageRun: request.run,
//       applyManageDataSource: request.data?.rows || [],
//       applyManageLoading: request.loading,
//       applyManageTableProps: request.tableProps,
//     };
//   };

//   return {
//     getApplyManageService,
//   };
// };

/** 组件评标委员会 */
export const ExpertManageService = (curRes) => {
  const request = useRequest(
    (requestParams?: Record<string, any>) => {
      let params: any = {
        current: 1,
        pageSize: 10,
        isOpen: 1,
        sort: 'createTime',
        order: 'desc',
        ...ExpertsManageCurRes(curRes),
        ...requestParams,
      };
      const reqUrl = `${baseUrl}/expertInfoController/dataGrid/${params?.params}`;

      delete params['applyFormNameDept'];
      delete params['applyFormNameUser'];
      if (params['createrID']?.length) {
        params['createrID'] = params['createrID']?.toString();
      } else {
        delete params['createrID'];
      }
      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: false,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  const data = useMemo(() => {
    if (request.data?.rows) {
      request.data?.rows?.forEach((item) => {
        // 给一个新值，然后删除id，在新增的时候不需要，只要expertID字段
        item.expertID = item?.id;
        item.mockID = generateRandomNumber('experts_');
        item.expertFlag = 0;
        delete item?.['id'];
      });
      return request.data?.rows;
    } else {
      return [];
    }
  }, [request.data?.rows]);

  return {
    expertRun: request.run,
    expertDataSource: data,
    expertLoading: request.loading,
    expertTableProps: request.pagination,
  };
};

/**获取包数据 */
export const getPackService = () => {
  const request = useRequest(
    (payload: any) => {
      let reqUrl = `${baseUrl}/purchasePackController/getPackDetails`;
      let params = {
        ...payload,
        dicTypeIds: `${getTenantID()}${ILoadMapTypeAll?.MATERIAL_TYPE}`,
      };
      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: true,
    },
  );
  return {
    getPackRun: request.run,
    getPackLoading: request.loading,
  };
};
